package com.pashanhoo.Thread.pool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**手写简易的线程池
 * @author 胡庆安
 * @version V1.0
 * @Package com.pashanhoo.Thread.pool
 * @date 2020/10/23 10:57
 * @Copyright © 2010-2020 爬山虎科技（扬州）股份有限公司
 */
public class HqaPool {
    Logger log = LoggerFactory.getLogger(Test.class);

    /**
     * 核心线程数
     */
    int coreSize;

    /**
     * 超时时间
     */
    long timeOut;

    TimeUnit timeUnit;

    HashSet<Worker> workers = new HashSet<>();

    BlockingQueue taskQueue;

    public HqaPool(int coreSize, int capcity, long timeOut,TimeUnit timeUnit) {
        this.coreSize = coreSize;
        this.timeOut = timeOut;
        this.timeUnit = timeUnit;
        taskQueue = new BlockingQueue(capcity);
    }

    //执行任务
    public void execute(Runnable task){
        synchronized (workers){
            //如果任务没有超过coreSize,直接交给Task对象执行
            if(workers.size()<coreSize){
                Worker worker = new Worker(task);

                workers.add(worker);
                worker.start();
            }else {//如果任务超过了coreSize,直接添加到队列等待
                taskQueue.offer(new Worker(task),timeOut,timeUnit);
                System.out.println("任务"+task+"被添加到了队列里");
            }
        }
    }

    /**
     * 阻塞任务队列（存放任务）
     */
    class BlockingQueue {

        private Deque<Worker> queue = new ArrayDeque<Worker>();
        public ReentrantLock lock = new ReentrantLock();
        private int capcity;
        //生产者条件变量
        private Condition fullWaitSet = lock.newCondition();
        //消费者条件变量
        private Condition emptyWaitSet = lock.newCondition();

        public BlockingQueue(int capcity) {
            this.capcity = capcity;

        }

        //任务放入阻塞队列(带超时)
        public boolean offer(Worker worker, long timeOut, TimeUnit timeUnit) {
            lock.lock();
            try {
                long nanos = timeUnit.toNanos(timeOut);
                while (queue.size() == capcity) {
                    try {
                        if (nanos <= 0) {
                            return false;
                        }
                        log.debug("等待加入任务队列 {} ...", worker);
                        nanos = fullWaitSet.awaitNanos(nanos);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("加入任务队列 {}", worker);
                queue.addLast(worker);
                emptyWaitSet.signal();
                return true;
            } finally {
                lock.unlock();
            }

        }

        //任务取出阻塞队列(带超时)
        public Worker poll(long timeout, TimeUnit unit) {
            lock.lock();
            try {
                // 将 timeout 统一转换为 纳秒
                long nanos = unit.toNanos(timeout);
                while (queue.isEmpty()) {
                    try {
                        // 返回值是剩余时间
                        if (nanos <= 0) {
                            return null;
                        }
                        nanos = emptyWaitSet.awaitNanos(nanos);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Worker t = queue.removeFirst();
                fullWaitSet.signal();
                return t;
            } finally {
                lock.unlock();
            }
        }


    }
    /**
     * 线程池任务
     */
    class Worker extends Thread {
        private Runnable task;

        public Worker(Runnable task) {
            this.task = task;
        }

        @Override
        public void run() {
            // 执行任务
            // 1) 当 task 不为空，执行任务
            // 2) 当 task 执行完毕，再接着从任务队列获取任务并执行
            // while(task != null || (task = taskQueue.take()) != null) {
            while (task != null || (task = taskQueue.poll(timeOut, timeUnit)) != null) {
                try {
                    log.debug("正在执行...{}", task);
                    task.run();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    task = null;
                }
            }
            synchronized (workers) {
            log.debug("worker 被移除{}", this);
            workers.remove(this);
            }
        }
    }
}
